#define _XOPEN_SOURCE
#include <sys/types.h>
#include <pwd.h>
#include <shadow.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

static int ipmsg_login(uid_t uid, const char *passwd)
{
	char *encrypted, *correct = NULL;
	struct passwd pw, *pwbufp = NULL;
	struct spwd *sp = NULL;
	char buffer[1024];
	int ret = -1;

	ret = getpwnam_r("rainlx", &pw, buffer, sizeof buffer, &pwbufp);
	if (ret != 0) {
		fprintf(stderr, "%s\n", strerror(ret));
		ret = -1;
		goto end;
	}
	if (pwbufp == NULL) {
		printf("pwbufp == NULL\n");
		ret = -1;
		goto end;
	}
	sp = getspnam(pw.pw_name);
	correct = sp->sp_pwdp;
	printf("correct:\n%s\n", correct);
	encrypted = crypt (passwd, correct);
	printf("encrypted:\n%s\n", encrypted);
	printf("%p\n", encrypted);
	if (strcmp(encrypted, correct)) {
		printf("password is incorrect\n");
		ret = -1;
		goto end;
	}
	encrypted = crypt (passwd, correct);
	printf("%p\n", encrypted);
	ret = 0;
end:
	return ret;
}

int main(int argc, char **argv)
{
	char buffer[1024];

	memset(buffer, 0, sizeof buffer);
	fgets(buffer, sizeof buffer, stdin);
	buffer[strlen(buffer) - 1] = '\0';
	printf("%d\n", ipmsg_login(1000, buffer));
	return 0;
}
